package com.libgdxbar.pvzlikegame.screens.gamescreens;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.utils.ScreenUtils;
import com.libgdxbar.pvzlikegame.entities.EntityGroup;
import com.libgdxbar.pvzlikegame.objects.TextureSplashLogo;
import com.libgdxbar.pvzlikegame.screens.GameScreen;
import com.libgdxbar.pvzlikegame.screens.GameScreenAdapter;

public class SplashScreen extends GameScreenAdapter {
	private EntityGroup getEntities(){ return EntityGroup.getInstance();}
	private TextureSplashLogo logo;
	private SplashSimpleAnim anim;
	private Class<? extends GameScreen> nextScreenKey = UISkinThemeScreen.class;

	static class SplashSimpleAnim {
		float duration = 1f;//秒
		float t;
		float startR = 1;
		float endR = 0.2f;
		Runnable onCompleted;

		public float step(float delta) {
			t += delta;

			float normalTime = t / duration;
			float interpolation = lerp(startR, endR, normalTime);
			if (normalTime > 1) onCompleted.run();
			return interpolation;
		}

		public void reset() {
			t = 0;
		}

		public float lerp(float a, float b, float t) {
			return a + (b - a) * t;
		}
	}

	@Override
	public void create() {
		logo = new TextureSplashLogo();
		logo.setScl(1, 1);
		logo.setCenterPosition(getViewCenter().x, getViewCenter().y);
		anim = new SplashSimpleAnim();
		anim.onCompleted = () -> {
			screenManager.setCurScreen(nextScreenKey);
		};
	}

	@Override
	public void render(float delta) {
		ScreenUtils.clear(0.2f, 0.2f, 0.2f, 1f);

		getEntities().update(delta);

		Batch batch = getEntities().batch;
		Color color = batch.getColor();
		float oldA = color.a;
		color.a = anim.step(delta);
		batch.setColor(color);

		getEntities().render(getViewport().getCamera());

		color.a = oldA;
		batch.setColor(color);
	}

	@Override
	public void show() {
		super.show();
		anim.reset();
		getEntities().add(logo);
	}

	@Override
	public void hide() {
		super.hide();
		getEntities().remove(logo);
	}

	@Override
	public void dispose() {
		if (logo != null) logo.dispose();
	}

}
